//
//  TheFatherViewController.m
//  PingTu
//
//  Created by Yangfan on 15/2/5.
//  Copyright (c) 2015年 4gread. All rights reserved.
//

#import "TheFatherViewController.h"
#import "PintuView.h"
#import "FreeView.h"
#import "PinJieView.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <ShareSDK/ShareSDK.h>

@interface TheFatherViewController ()

@end

@implementation TheFatherViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [D_Main_Appdelegate hiddenPreView];
    

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [D_Main_Appdelegate showPreView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initialization];
    [self navigationView];
    [self DataLoad];
    [self UI];
}

// 初始化参数
- (void)initialization {
    [self.view setBackgroundColor:[UIColor whiteColor]];
    originImageSize = 0;
}

// 导航栏设置
- (void)navigationView {
    
    // 底部的高斯模糊的图片
    imageViewBack = [[UIImageView alloc] init];
    [imageViewBack setFrame:self.view.bounds];
    [imageViewBack setImage:[UIImage imageNamed:@"morenBack.jpg"]];
    [self.view addSubview:imageViewBack];
    
    // 左边的返回相册按钮
    UIButton *backLibrary = [[UIButton alloc] init];
    backLibrary.tag = 0;
    [backLibrary setFrame:CGRectMake(0, 0, 78, 44)];
    [backLibrary setBackgroundImage:[UIImage imageNamed:@"backToLibrary"] forState:UIControlStateNormal];
    [backLibrary setBackgroundImage:[UIImage imageNamed:@"backToLibrary"] forState:UIControlStateHighlighted];
    [backLibrary addTarget:self action:@selector(backLibraryOrSaveAndShare:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backLibrary];
    
    // 右边的保存和分享按钮
    UIButton *saveAndShare = [[UIButton alloc] init];
    saveAndShare.tag = 1;
    [saveAndShare setFrame:CGRectMake(Kwidth - 112, 0, 112, 44)];
    [saveAndShare setBackgroundImage:[UIImage imageNamed:@"saveAndShare"] forState:UIControlStateNormal];
    [saveAndShare setBackgroundImage:[UIImage imageNamed:@"saveAndShare"] forState:UIControlStateHighlighted];
    [saveAndShare addTarget:self action:@selector(backLibraryOrSaveAndShare:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveAndShare];
}

// 数据初始化
- (void)DataLoad {
}

// 开始布局界面
- (void)UI {
    // 底部的三个功能区选择
//    UIImageView *bottomSectionImageView = [[UIImageView alloc] init];
//    [bottomSectionImageView setUserInteractionEnabled:YES];
//    [bottomSectionImageView setFrame:CGRectMake(0, Kheight - 39, Kwidth, 39)];
//    [bottomSectionImageView setImage:[UIImage imageNamed:@"bottomSection"]];
//    [self.view addSubview:bottomSectionImageView];
    bottomBackView = [[UIView alloc] initWithFrame:CGRectMake(0, Kheight - 39, Kwidth, 39)];
    [bottomBackView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:bottomBackView];
    
    UIButton *sectionButton;
    for (int i = 1; i < 3; i++) {
        sectionButton = [[UIButton alloc] init];
        [sectionButton setTag:i];
        [sectionButton setFrame:CGRectMake((i - 1) * (Kwidth / 2.0), 0, Kwidth / 2.0, 39)];
        switch (i) {
            case 1:
//                [sectionButton setTitle:@"拼图" forState:UIControlStateNormal];
            {
                if (Kwidth < 350) {
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuUnSec640"] forState:UIControlStateNormal];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuUnSec640"] forState:UIControlStateHighlighted];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuSec640"] forState:UIControlStateSelected];
                } else if (Kwidth > 350 && Kwidth < 400) {
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuUnSec750"] forState:UIControlStateNormal];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuUnSec750"] forState:UIControlStateHighlighted];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pintuSec750"] forState:UIControlStateSelected];
                }
                
                [sectionButton setSelected:YES];
            }
                break;
            case 2:
//                [sectionButton setTitle:@"xxx" forState:UIControlStateNormal];
            {
                if (Kwidth < 350) {
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieUnSec640"] forState:UIControlStateNormal];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieUnSec640"] forState:UIControlStateHighlighted];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieSec640"] forState:UIControlStateSelected];
                } else if (Kwidth > 350 && Kwidth < 400) {
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieUnSec750"] forState:UIControlStateNormal];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieUnSec750"] forState:UIControlStateHighlighted];
                    [sectionButton setBackgroundImage:[UIImage imageNamed:@"pinjieSec750"] forState:UIControlStateSelected];
                }
            }
                break;
//            case 2:
//                [sectionButton setTitle:@"拼接" forState:UIControlStateNormal];
//                break;
            default:
                break;
        }
//        [sectionButton setTitleColor:HexRGB(0x718d06) forState:UIControlStateNormal];
        [sectionButton addTarget:self action:@selector(whichSection:) forControlEvents:UIControlEventTouchUpInside];
//        [bottomSectionImageView addSubview:sectionButton];
        [bottomBackView addSubview:sectionButton];
    }
}

#pragma mark - 导航栏和底部功能区域的点击事件
- (void)backLibraryOrSaveAndShare:(UIButton *)sender {
    if (sender.tag == 0) {// 返回相册
        [self.navigationController popViewControllerAnimated:YES];
    } else if(sender.tag == 1) {// 保存和分享
        switch (whichFunction) {
            case 1:
                image = [self captureScrollView:nil orUIView:[(PintuView *)[self.view viewWithTag:8765 + 1] mainContentView]];// 拼接
                break;
            case 2:
                image = [self captureScrollView:[(PinJieView *)[self.view viewWithTag:8765 + 2] pinJieContentScrollView] orUIView:nil];// 拼接
                break;
            default:
                break;
        }
        

        
        //构造分享内容
        id<ISSContent> publishContent = [ShareSDK content:@"拼图"
                                           defaultContent:@"拼图"
                                                    image:[ShareSDK jpegImageWithImage:image quality:1]
                                                    title:@"拼图"
                                                      url:nil
                                              description:nil
                                                mediaType:SSPublishContentMediaTypeImage];
        //创建弹出菜单容器
        id<ISSContainer> container = [ShareSDK container];
        [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
        
        //弹出分享菜单
        [ShareSDK showShareActionSheet:container
                             shareList:nil
                               content:publishContent
                         statusBarTips:YES
                           authOptions:nil
                          shareOptions:nil
                                result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                    
                                    if (state == SSResponseStateSuccess) {
                                        [self showHUD:@"分享成功"];
                                    }
                                    else if (state == SSResponseStateFail) {
                                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"图片分享到相应的应用客户端，请先安装客户端: )" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
                                        [alert show];

                                    }
                                }];

        // 保存到相册
        BOOL isSaved;
        if (originImageSize == UIImageJPEGRepresentation(image, 1.0).length) {
            isSaved = YES;
        } else {
            isSaved = NO;
        }
        if (isSaved) {
            [self showHUD:@"已经保存"];
        } else {
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
        }
        // 将图片的大小进行保存
        originImageSize = UIImageJPEGRepresentation(image, 1.0).length;
    }
}




- (void)firstInto {
    UIButton *button = [[UIButton alloc] init];
    button.tag = 1;
    [self whichSection:button];
}

- (void)whichSection:(UIButton *)sender {
//    [HUD showAnimated:YES whileExecutingBlock:^{
//        sleep(1);
//    } completionBlock:^{
//        //        [HUD removeFromSuperview];
//        //        HUD = nil;
//    }];


    whichFunction = sender.tag;
    [sender setSelected:YES];
    if (sender.tag == 1) {
        [(UIButton *)[bottomBackView viewWithTag:2] setSelected:NO];
    } else {
        [(UIButton *)[bottomBackView viewWithTag:1] setSelected:NO];
    }
    BaseView *contentView;
    // 判断点击的当前图片是否已经加载，如果已经加载在之前，则将View图层调到View的最前面显示
    contentView = (BaseView *)[self.view viewWithTag:8765 + sender.tag];
    if (contentView != nil) {
        [contentView setHidden:NO];
        [self.view bringSubviewToFront:contentView];
        switch (sender.tag) {
            case 1:
            {
                contentView = (BaseView *)[self.view viewWithTag:8765 + 2];
                [contentView setHidden:YES];
//                contentView = (BaseView *)[self.view viewWithTag:8765 + 2];
//                [contentView setHidden:YES];
            }
                break;
            case 2:
            {
//                contentView = (BaseView *)[self.view viewWithTag:8765 + 2];
//                [contentView setHidden:YES];
                contentView = (BaseView *)[self.view viewWithTag:8765 + 1];
                [contentView setHidden:YES];
            }
                break;
//            case 2:
//            {
//                contentView = (BaseView *)[self.view viewWithTag:8765 + 1];
//                [contentView setHidden:YES];
//                contentView = (BaseView *)[self.view viewWithTag:8765 + 0];
//                [contentView setHidden:YES];
//            }
//                break;
                
            default:
                break;
        }
        return;
    } else {
        contentView = (BaseView *)[self.view viewWithTag:8765 + 1];
        [contentView setHidden:YES];
        contentView = (BaseView *)[self.view viewWithTag:8765 + 2];
        [contentView setHidden:YES];
//        contentView = (BaseView *)[self.view viewWithTag:8765 + 2];
//        [contentView setHidden:YES];
    }// 如果是首次进来，则开始没有加载，这个时候添加新的加载执行下面的代码
    CGRect contentRect = CGRectMake(0, 44, Kwidth, Kheight - 44 - 39);
    PintuView *pintuView;
    FreeView *freeView;
    PinJieView *pinJieView;
    switch (sender.tag) {
        case 1: {
            pintuView = [[PintuView alloc] initWithFrame:contentRect];
            [pintuView setTag:8765 + sender.tag];
            [pintuView setAssetsIntoPintuView:_assets];
            [self.view addSubview:pintuView];
        }
            break;
//        case 1: {
//            freeView = [[FreeView alloc] initWithFrame:contentRect];
//            [freeView setAssets:_assets];
//            [freeView setTag:8765 + sender.tag];
//            [self.view addSubview:freeView];
//        }
            break;
        case 2: {
            pinJieView = [[PinJieView alloc] initWithFrame:contentRect];
            [pinJieView setAssetsIntoPintuView:_assets];
            [pinJieView setTag:8765 + sender.tag];
            [self.view addSubview:pinJieView];
        }
            break;
        default:
            break;
    }
}

// 获取用户拼接的图片
- (UIImage *)captureScrollView:(UIScrollView *)scrollView orUIView:(UIView *)inputView{
    UIImage* image = nil;
    if(UIGraphicsBeginImageContextWithOptions != NULL)
    {
        if (scrollView != nil) {
            UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, 2.0);
        } else {
            UIGraphicsBeginImageContextWithOptions(inputView.frame.size, NO, 2.0);
        }
    } else {
        if (scrollView != nil) {
            UIGraphicsBeginImageContext(scrollView.contentSize);
        } else {
            UIGraphicsBeginImageContext(inputView.frame.size);
        }
    }
    {
        if (scrollView != nil) {
            CGPoint savedContentOffset = scrollView.contentOffset;
            CGRect savedFrame = scrollView.frame;
            scrollView.contentOffset = CGPointZero;
            scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
            
            [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
            image = UIGraphicsGetImageFromCurrentImageContext();
            
            scrollView.contentOffset = savedContentOffset;
            scrollView.frame = savedFrame;
        } else {
            [inputView.layer renderInContext: UIGraphicsGetCurrentContext()];
            image = UIGraphicsGetImageFromCurrentImageContext();
        }
    }
    UIGraphicsEndImageContext();
    
    if (image != nil) {
        return image;
    }
    return nil;
}

#pragma mark - savePhotoAlbumDelegate
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *) contextInfo {
    if (error != nil) {
        return;
    }
    [self showHUD:@"成功保存本地"];
}

- (void)showHUD:(NSString *)word{
    // 本地图片保存成功提示
    if (HUD != nil) {
        [HUD removeFromSuperview];
    }
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.yOffset = -100.0f;
    [self.view addSubview:HUD];
    //    HUD.dimBackground = YES;
    HUD.labelText = word;
    HUD.mode = MBProgressHUDModeText;
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
//        [HUD removeFromSuperview];
//        HUD = nil;
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
